<template>
  <div class="app">
    <RouterView />
  </div>
</template>

<script setup lang="ts">
import io from 'socket.io-client';
import eventBus from "./util/eventBus"
import { userStore } from "./store/index"
const store = userStore()




const socketHandler = () => {
  // 连接消息服务
  let socket = io('ws://'+ location.host, {
    query: {
      userName: store.$state.userInfo.username
    }
  });/* 建立连接 */

  window.addEventListener("beforeunload",()=>{
  localStorage.setItem("xxxxxxxxxx","ccccc22ccccccc")
  socket.close()
})


  let id = Math.random()
  sessionStorage.setItem("myid", id.toString())
  socket.on("connection", () => {
    console.log("连接成功");
  })
  if (socket) {
    store.saveSocket(socket)
  }
  eventBus.on('send', (res) => {
    console.log("发送~~~~~~~~~~~~~~~~", res);
    socket.emit("message",
      JSON.stringify({
        id: store.$state.userInfo.username,
        msg: res,
        sendTime: new Date().getTime()
      }))
  })

  socket.on("resMsg", res => {
    console.log("接收到消息", res);
    store.saveMessage(res)
  })

}
// store存在
if(store.$state.userInfo.username){
  socketHandler()
}
// 监听开启socket连接
eventBus.on("connectSocket",()=>{
  socketHandler()
})

</script>
<style>
.app {
  height: 100vh;
  width: 100vw;
  margin: 0px;
  padding: 0px;
}
</style>